package com.dataart.productshop.dao.impl;

import com.dataart.productshop.dao.BaseDao;
import com.dataart.productshop.model.boiko.informationsystem.Subject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;

import java.util.List;


public class BaseDaoImpl<T> implements BaseDao<T>{

	protected final Log log = LogFactory.getLog(getClass());
	private Class<T> persistentClass;
	private HibernateTemplate hibernateTemplate;
	private SessionFactory sessionFactory;
	
	public BaseDaoImpl(final Class<T> persistantClass ) {
		this.persistentClass = persistantClass;
	}
	
	@Autowired
    @Required
    public void setSessionFactory(SessionFactory sessionFactory){
		 this.sessionFactory = sessionFactory;
	     this.hibernateTemplate = new HibernateTemplate(sessionFactory); 
	}
	
	@Override
	public T getById(Long id) {
		T entity = (T) hibernateTemplate.get(this.persistentClass, id);

		if (entity == null) {
			log.warn("Uh oh, '" + this.persistentClass + "' object with id '"
					+ id + "' not found...");
			throw new ObjectRetrievalFailureException(this.persistentClass, id);
		}

		return entity;

	}

	@Override
	public void save(T entity) {
		sessionFactory.getCurrentSession().saveOrUpdate(entity);
		
	}

	@Override
	public List<T> getAll() {
		 return hibernateTemplate.loadAll(this.persistentClass);
	}
	
	
	@Override
	public void delete(Long id) {
			getHibernateTemplate().delete(this.getById(id));
	}
	
	
	public HibernateTemplate getHibernateTemplate() {
        return this.hibernateTemplate;
    }
	
    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }
    
	public Criteria createCriteria(Class<?> clazz){
    	return sessionFactory.getCurrentSession().createCriteria(clazz);
    }

}
